<template>
  <div class="pt10 pb10">
    <div
      class="pr35 ell item rel"
      v-for="(i, index) in composerAllList"
      :key="index"
      @click="handleNodeClick(i)"
    >
      <div class="g6 ks-row-left">
        <span>名称：</span>
        <el-button
          class="ell"
          type="text"
          style="margin-top: -7px"
          @click="openBlockEditor(i)"
          :title="i.eventName"
        >
          {{ i.eventName }}</el-button
        >
      </div>
      <div class="g6 ell" :title="i.composerKey">标识：{{ i.composerKey }}</div>
      <el-divider
        v-if="index < composerAllList.length - 1"
        class="mt5"
      ></el-divider>
      <div></div>
      <div class="designer-block__item-actions">
        <el-popconfirm
          placement="top"
          title="确认删除当前逻辑编排"
          @confirm="handleBlocklyDelete(i, index)"
        >
          <el-button slot="reference" type="text" size="mini">删除</el-button>
        </el-popconfirm>
      </div>
    </div>
    <BlockEditor ref="BlockEditor"></BlockEditor>
  </div>
</template>

<script>
import BlockEditor from "@/components/blockly/BlockEditor";
import { mapActions, mapGetters } from "vuex";
import { cloneDeep } from "lodash";
import { treeToArray } from "@/utils/util";
import MicroBlocklyEditor from "@/components/BlocklyEditor";
import { Popconfirm } from "element-ui";

export default {
  props: ["composerList"],
  components: { BlockEditor, [Popconfirm.name]: Popconfirm },
  data() {
    return {
      componentItem: {}, // 当前选中的组件
    };
  },
  computed: {
    ...mapGetters(["getModelTreeList", "getModelForm", "getFormId"]),
    composerAllList() {
      return this.composerList
      // const comList = this.getAllComposerList();
      // const filterRes = [];
      // for (let i = 0; i < this.composerList.length; i++) {
      //   const com = this.composerList[i];
      //   const flag = comList.some(
      //     (item) =>
      //       com.componentId === item.key || item.composerKey === com.composerKey
      //   );
      //   if (flag) {
      //     filterRes.push(com);
      //   } else {
      //     this.composerList.splice(i, 1);
      //     i--;
      //   }
      // }
      // return filterRes;
    },
  },
  async mounted() {},
  methods: {
    ...mapActions(["setModelForm", "setForm"]),
    async openBlockEditor(item) {
      this.handleNodeClick(item);
      await this.$nextTick();
      // item里面可以拿到函数名
      const composerData = item;

      // ** start 编辑时判断编排版本 since v2.7.1 **
      if (composerData._MicroApp) {
        MicroBlocklyEditor.openForDesktop(composerData);
        return;
      }
      // ** end **

      const eventData = item;
      const that = this;
      this.$refs.BlockEditor.open(eventData, {}, (data) => {
        // 更新组件逻辑编排名称
        let eventItem = null;
        if (data.composerKey.startsWith("tb_o_click")) {
          // 表格的操作按钮
          that.componentItem && (that.componentItem.eventName = data.eventName);
        } else {
          // 正常添加事件的组件
          const currentEventValue = item.event.value;
          const eventList = that.componentItem?.__highSetUp?.events || [];
          const eventArr = eventList.find(
            (event) => event.value === currentEventValue
          );
          if (eventArr?.children) {
            eventItem = eventArr.children?.find(
              (event) => event.composerKey === item.composerKey
            );
          }
          eventItem && (eventItem.eventName = data.eventName);
        }

        // 将变更之后的数据保存到全局
        composerData.eventName = data.eventName;
        composerData.eventXml = data.eventXml;
        composerData.eventJs = encodeURIComponent(data.eventJs);
      });
    },
    treeFind(tree, componentId) {
      for (const data of tree) {
        if (data.key === componentId) return data;
        let res;
        if (data.tagName === "hlTableList") {
          const list = data?.__config?.operate?.customBtn || [];
          if (list.length) {
            res = list.find((item) => item.composerKey === componentId);
          }
          if (res) return res;
        } else if (data.children) {
          res = this.treeFind(data.children, componentId);
          if (res) return res;
        }
      }
      return null;
    },
    // 手动选中当前节点
    handleNodeClick(composerData) {
      // 获取组件对象
      const componentItem = this.treeFind(
        this.getModelTreeList,
        composerData.componentId
      );
      // 表格的操作按钮现在获取不到
      if (!componentItem) return;
      this.componentItem = componentItem;
      // 当点击表单内组件当时候需要处理好表单所属业务模型的数据模型数据
      if (componentItem.isFormLayout) {
        const { modelCode, children } = this.getFormModelCodeInTree(
          componentItem.key,
          this.getModelTreeList
        );
        this.$store.commit("changeFormList", children);
        if (this.getFormId !== modelCode) {
          // 表单组件逻辑
          this.setForm(modelCode);
        }
      }
      if (componentItem.key !== this.getModelForm.key) {
        this.setModelForm({});
      }
      this.setModelForm(componentItem);
    },

    /**
     *  在tree中 根据 组件key 定位所点击组件所在的form
     * @param {*} key
     * @param {*} treelist
     * @returns  返回组件所在formlayout  的   modelCode  和 children
     */
    getFormModelCodeInTree(key, treelist) {
      let queen = [];
      let node = null;
      queen = queen.concat(treelist);
      while (queen?.length > 0) {
        const item = queen.shift();
        if (item._TYPE_ === "org") {
          node = item.node;
        } else if (item.key === key && !!node) {
          queen = [];
        } else if (item.children) {
          const org = [];
          if (
            item.tagName === "hlTableAdd" ||
            item.tagName === "hlLayoutForm"
          ) {
            org.push({ node: cloneDeep(node), _TYPE_: "org" });
            const nodeCode = item.__config.modelCode || item.__config.code; // 兼容老业务
            !!nodeCode &&
              (node = { modelCode: nodeCode, children: item.children });
          }
          queen = [].concat(item.children, org, queen);
        }
      }
      return node;
    },
    getAllComposerList() {
      const comList = treeToArray(this.getModelTreeList);
      let temp = [];
      comList.forEach((com) => {
        if (com.tagName === "hlTableList") {
          // 表格自定义按钮
          const btnList = com?.hlcustomBtn?.children || [];
          if (btnList.length) {
            temp = temp.concat(btnList);
          }
          // 表格操作按钮
          const list = com?.__config?.operate?.customBtn || [];
          if (list.length) {
            temp = temp.concat(list);
          }
        }
      });
      return comList.concat(temp);
    },

    /**
     * 逻辑编排删除
     * since v2.7.1
     */
    handleBlocklyDelete(i) {
      const index = this.composerList.findIndex(
        (item) => item.composerKey === i.composerKey
      );
      if (index > -1) {
        this.composerList.splice(index, 1);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.item:hover {
  background-color: #f3f9ff;
}

.designer-block__item-actions {
  position: absolute;
  top: 50%;
  right: 12px;
  transform: translateY(-50%);
}
</style>
